package com.old.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.old.dto.VideoInsertDTO;
import com.old.dto.VideoQueryDTO;
import com.old.entity.Video;
import com.old.mapper.PostMapper;
import com.old.mapper.UserMapper;
import com.old.mapper.VideoMapper;
import com.old.result.PageBean;
import com.old.service.VideoService;
import com.old.vo.VideoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class VideoServiceImpl implements VideoService {
    private final VideoMapper videoMapper;
    private final ObjectMapper objectMapper;
    private final UserMapper userMapper;

    private final PostMapper postMapper;


    @Override
    public void addVideo(VideoInsertDTO videoInsertDTO) {
        Video video = new Video();
        BeanUtils.copyProperties(videoInsertDTO, video);
        videoMapper.insertVideo(video);
    }

    //查询戏曲内容详情
    @Override
    public VideoVO getVideoDetail(Integer videoId, Integer userId) {
     //   VideoVO videoVO = new VideoVO();
       // Video videoDetail = videoMapper.getVideoDetail(videoId);
        //BeanUtils.copyProperties(videoDetail, videoVO);
        VideoVO videoVO=videoMapper.findOperaDetailById(videoId);
        //判断是否查询成功
        if (videoVO == null){
            log.info("查询失败");
            throw new RuntimeException("查询失败");
        }

        //判断是否传入userid
        if (userId == null || userId <= 0) {
            //未传入
            //设置未点赞
            videoVO.setIsgood(false);
            //设置点赞数=0
            videoVO.setLikeMan(String.valueOf(0));
        } else {
            //传入userid
            //从vo获取点赞列表
            String likeMen = videoVO.getLikeMan();
            //点赞空判定
            if (likeMen == null || likeMen.isEmpty()) {
                //空点赞
                videoVO.setIsgood(false);
                //设置点赞数=0
                videoVO.setLikeMan(String.valueOf(0));
            }
            if (!likeMen.equals("[]")) {
                List<Integer> list = parseStringToIntList(likeMen);
                videoVO.setIsgood(list != null && list.contains(userId));
            }
        }
        return videoVO;
    }

    public List<Integer> parseStringToIntList(String s) {
        // 1. 去除方括号
        String cleaned = s.replaceAll("[\\[\\]]", ""); // 结果: "1,2"
// 2. 按逗号分割字符串
        String[] parts = cleaned.split(",");
// 3. 转换为List<Integer>
        List<Integer> list = new ArrayList<>();
        for (String part : parts) {
            list.add(Integer.parseInt(part.trim())); // trim() 处理可能的空格
        }
        return list;
    }

    /**
     * 分页查询戏曲列表
     *
     * @param pageNo
     * @param pageSize
     * @param sortBy
     * @param searchTerms
     * @param userId
     * @return
     */
    @Override
    public PageBean getVideoList(Integer pageNo, Integer pageSize, Integer sortBy, String searchTerms, Integer userId) throws JsonProcessingException {
//        PageHelper.startPage(pageNo, pageSize);
//        List<VideoVO> list = videoMapper.list(String.valueOf(sortBy), searchTerms);
//        Page<VideoVO> p = (Page<VideoVO>) list;
//        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
//        List list_init = pageBean.getList();
//
//        for (Object o : list_init) {
//            VideoVO videoVO = (VideoVO) o;
//
//            // 解析参与人数
//            ObjectMapper objectMapper = new ObjectMapper();
//            // 解析为JsonNode对象
//            if (videoVO.getLikeMan() != null) {
//                JsonNode jsonNode = objectMapper.readTree(videoVO.getLikeMan());
//
//                // 获取数组元素个数
//                int elementCount = jsonNode.size();
//
//                videoVO.setLikeMan(Integer.toString(elementCount));
//                // 判断用户是否点赞过
//                if (userId != null && videoVO.getLikeMan().contains(userId.toString())) {
//                    videoVO.setIsgood(true);
//                } else {
//                    videoVO.setIsgood(false);
//                }
//            }
//
//        }
//        return new PageBean(p.getTotal(), list_init);
        return pageList(pageNo, pageSize, sortBy, searchTerms, userId);
    }

    @Override
    public PageBean getVideoListById(VideoQueryDTO videoQueryDTO) {
        //分页查询
        PageHelper.startPage(videoQueryDTO.getPageNo(), videoQueryDTO.getPageSize());
        Page<Video> page = videoMapper.videoListPage(videoQueryDTO);

        long total = page.getTotal();
        List<Video> records = page.getResult();

        return new PageBean(total, records);
    }

    @Override
    @Transactional
    public void deleteVideo(Integer videoId, Integer userId) {
        // 1. 查询戏曲是否存在
        Video video = videoMapper.checkVideoExist(videoId);
        if (video == null) {
            throw new RuntimeException("戏曲不存在");
        }

        // 2. 检查当前用户是否有权限删除戏曲
        // 管理员判定+作者判定
        if (userMapper.findByID(userId).getStatus().equals(0) || video.getAuthorId().equals(userId)) {
            // 3. 删除戏曲
            videoMapper.deleteVideo(videoId);
            log.info("{}用户删除视频{}", userId, videoId);
        } else {
            log.info("非作者/管理员");
            throw new RuntimeException("无权限删除");
        }


    }

    @Override
    public PageBean pageList(Integer pageNo, Integer pageSize, Integer sortBy, String searchTerms, Integer userId) throws JsonProcessingException {
        PageHelper.startPage(pageNo, pageSize);

//        Map<String, Object> map = ThreadLocalUtil.get();
//        Integer userId = (Integer) map.get("id");
        String sort = "";
        if (sortBy == 0) {
            sort = "video.create_time";
        }
        if (sortBy == 1) {
            sort = "video.likes";
//            sort ="`like`" ;
        }

        List<VideoVO> list = videoMapper.list(sort, searchTerms);
        Page<VideoVO> p = (Page<VideoVO>) list;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        List list_init = pageBean.getList();

        for (Object o : list_init) {
            VideoVO videoVO = (VideoVO) o;

            // 解析参与人数
            ObjectMapper objectMapper = new ObjectMapper();
            // 解析为JsonNode对象
            if (videoVO.getLikeMan() != null) {
                JsonNode jsonNode = objectMapper.readTree(videoVO.getLikeMan());
                // 获取数组元素个数
                int elementCount = jsonNode.size();
                if (userId != null){

                    // 将字符串转换为JSONArray
                    JSONArray jsonArray = JSON.parseArray(videoVO.getLikeMan());

                    // 使用FastJSON内置方法检查元素是否存在
                    boolean isGood = jsonArray.contains(userId);

                    // 设置帖子的状态
                    videoVO.setIsgood(isGood);

                } else {
                    videoVO.setIsgood(false);
                }
//                if (userId != null && videoVO.getLikeMan().contains(userId.toString())) {
//                    videoVO.setIsgood(true);
//                } else {
//                    videoVO.setIsgood(false);
//                }
                videoVO.setLikeMan(Integer.toString(elementCount));
            }
        }
        return pageBean;
    }

    @Override
    //用于判定是否在点赞列表中
    public boolean isGood(Integer userId, Integer id) {
        String likeList = videoMapper.getLikeManByVideoId(id);
        return likeList.contains(userId.toString());
    }

    //点赞
    @Override
    @Transactional
    public Integer likeVideo(Integer videoId, Integer userId) {
        // 1. 获取当前点赞列表
        String likeManJson = videoMapper.getLikeManByVideoId(videoId);
        List<Integer> likeManList = parseLikeManJson(likeManJson);

        // 2. 检查是否已点赞
        if (likeManList.contains(userId)) {
            throw new RuntimeException("请勿重复点赞");
        }

        // 3. 添加用户ID到列表
        likeManList.add(userId);
        String newLikeManJson = toJsonString(likeManList);

        // 4. 更新数据库
        videoMapper.updateLikeMan(videoId, newLikeManJson);

        // 5. 返回最新点赞数
        return likeManList.size();
    }
    //批量删除戏曲
    @Override
    @Transactional // 事务注解
    public void deleteVideosByIds(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) return;
        videoMapper.batchDeleteByIds(ids);
    }

    //取消点赞
    @Override
    @Transactional
    public Integer cancelLike(Integer videoId, Integer userId) {
        // 1. 获取当前点赞列表
        String likeManJson = videoMapper.getLikeManByVideoId(videoId);
        List<Integer> likeManList = parseLikeManJson(likeManJson);

        // 2. 检查是否未点赞
        if (!likeManList.contains(userId)) {
            throw new RuntimeException("未点赞，无法取消");
        }

        // 3. 移除用户ID
        likeManList.remove(userId);
        String newLikeManJson = toJsonString(likeManList);

        // 4. 更新数据库
        videoMapper.updateLikeMan(videoId, newLikeManJson);

        // 5. 返回最新点赞数
        return likeManList.size();
    }

    // JSON 解析工具方法
    private List<Integer> parseLikeManJson(String json) {
        try {
            return objectMapper.readValue(json, new TypeReference<List<Integer>>() {
            });
        } catch (JsonProcessingException e) {
            log.error("JSON解析失败", e);
            return new ArrayList<>();
        }
    }

    private String toJsonString(List<Integer> list) {
        try {
            return objectMapper.writeValueAsString(list);
        } catch (JsonProcessingException e) {
            log.error("JSON序列化失败", e);
            return "[]";
        }
    }


}
